#define LOG_TAG "can.task"
#include "elog.h"

#include "can_task.h"
#include "cmsis_os2.h"
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "queue.h"

#include "../drivers/drv_can.h"
#include "j1939tp.h"
#include "j1939tp_config.h"

#include "power_can.h"
#include "bms_can.h"

extern SemaphoreHandle_t sync_sem;
pwr_t *get_pwr_struct(void);

osThreadId_t canTaskHandle;
const osThreadAttr_t canTask_attributes = {
    .name = "canTask",
    .stack_size = 1024 + 512,
    .priority = (osPriority_t)osPriorityHigh,
};

/**
 * @brief Function implementing the can thread.
 * @param argument: Not used
 * @retval None
 */
/* USER CODE END Header_can_task */
void cantask(void *argument)
{
    /* USER CODE BEGIN can_task */
    pwr_t *pwr = get_pwr_struct();
    stm32_can_start();
    j1939_init();
    if (j1939_init_ready())
    {
        log_d("j1939 init success.");
    }
    bms_init();
    power_init();
    /* 释放二值信号量，用于任务同步 */
    xSemaphoreGive(sync_sem);

    /* Infinite loop */
    for (;;)
    {
        RUN_PERIODIC_TASK(pwr_read_state(), 100u);
        RUN_PERIODIC_TASK(pwr_read_sys_voltage(), 30u);
        RUN_PERIODIC_TASK(pwr_read_ac_voltage(), 250u);
        if (pwr->set.enable)
        {
            pwr_set_fsm(pwr);
        }
        osDelay(5u);
    }
    /* USER CODE END can_task */
}
